import SwiftUI

struct ScenarioListView: View {
    @EnvironmentObject var sensor: SensorRecorder
    @AppStorage("userName") private var userName: String = ""
    
    @State private var selectedScenario: Scenario?
    @State private var pendingDuration: Double = 60
    @State private var activeScenario: Scenario?
    @State private var showFreeRecording: Bool = false
    
    @State private var showCountdown: Bool = false
    @State private var countdownValue: Int = 3
    
    @State private var isRecording: Bool = false
    @State private var recordingProgress: Double = 0
    @State private var recordingStartDate: Date?
    @State private var recordingTotalSec: Double = 60
    @State private var timer: Timer?
    
    @State private var showNoteSheet: Bool = false
    @State private var noteText: String = ""
    @State private var lastSession: Session?
    @State private var sessions: [Session] = []
    @State private var isUploading: Bool = false
    @State private var uploadError: String?
    @State private var uploadSuccess: Bool = false
    @State private var hasFinishedRecording: Bool = false  // 标记是否已完成记录但未上传
    @State private var showAirPodsAlert: Bool = false  // 显示 AirPods 未连接警告
    
    private let columns = [
        GridItem(.flexible(), spacing: 16),
        GridItem(.flexible(), spacing: 16)
    ]
    
    private var backgroundGradient: some View {
        LinearGradient(
            colors: [.black.opacity(0.95), .blue.opacity(0.5)],
            startPoint: .topLeading,
            endPoint: .bottomTrailing
        )
        .ignoresSafeArea()
    }

// MARK: - Recording Full Screen Child View
private struct RecordingFullScreenView: View {
    @ObservedObject var sensor: SensorRecorder
    @Binding var isRecording: Bool
    @Binding var hasFinishedRecording: Bool
    @Binding var recordingProgress: Double
    @Binding var recordingStartDate: Date?
    @Binding var recordingTotalSec: Double
    var stopAction: () -> Void
    var saveAction: () -> Void

    private var timeRemainingString: String {
        guard let start = recordingStartDate else { return "--:--" }
        let elapsed = Date().timeIntervalSince(start)
        let remaining = max(0, recordingTotalSec - elapsed)
        let m = Int(remaining) / 60
        let s = Int(remaining) % 60
        return String(format: "%02d:%02d", m, s)
    }

    private var progressGradient: AngularGradient {
        AngularGradient(
            colors: [.red, .orange, .yellow, .green, .cyan, .blue, .purple, .red],
            center: .center
        )
    }

    var body: some View {
        ZStack {
            LinearGradient(
                colors: [.black.opacity(0.95), .purple.opacity(0.5), .pink.opacity(0.3)],
                startPoint: .topLeading,
                endPoint: .bottomTrailing
            ).ignoresSafeArea()

            VStack(spacing: 20) {
                // 进度圆环和倒计时
                ZStack {
                    Circle()
                        .stroke(lineWidth: 10)
                        .foregroundColor(.white.opacity(0.08))
                        .frame(width: 180, height: 180)
                    Circle()
                        .trim(from: 0, to: recordingProgress)
                        .stroke(progressGradient, style: StrokeStyle(lineWidth: 10, lineCap: .round))
                        .rotationEffect(.degrees(-90))
                        .frame(width: 180, height: 180)
                        .animation(.easeInOut(duration: 0.2), value: recordingProgress)
                    VStack(spacing: 6) {
                        Image(systemName: "waveform.path.ecg")
                            .font(.system(size: 24, weight: .bold))
                            .foregroundColor(.white)
                        Text(timeRemainingString)
                            .font(.system(.title3, design: .rounded).weight(.semibold))
                            .foregroundColor(.white)
                        Text("\(sensor.sampleCount) 样本")
                            .font(.caption)
                            .foregroundColor(.white.opacity(0.7))
                    }
                }

                // 实时传感器数据折线图
                VStack(spacing: 12) {
                    RealtimeChartView(
                        title: "加速度计",
                        icon: "arrow.up.and.down.and.arrow.left.and.right",
                        color: .cyan,
                        xData: sensor.accXHistory,
                        yData: sensor.accYHistory,
                        zData: sensor.accZHistory
                    )
                    RealtimeChartView(
                        title: "陀螺仪",
                        icon: "gyroscope",
                        color: .orange,
                        xData: sensor.gyroXHistory,
                        yData: sensor.gyroYHistory,
                        zData: sensor.gyroZHistory
                    )
                }

                // 按钮
                HStack(spacing: 16) {
                    if isRecording {
                        Button(role: .destructive) { stopAction() } label: {
                            Label("提前结束", systemImage: "stop.circle.fill")
                        }
                        .buttonStyle(.bordered)
                    } else if hasFinishedRecording {
                        Button { saveAction() } label: {
                            Label("保存记录", systemImage: "square.and.arrow.down.fill")
                        }
                        .buttonStyle(.borderedProminent)
                    }
                }
            }
            .padding(24)
        }
    }
}
    
    private var progressGradient: AngularGradient {
        AngularGradient(
            colors: [.red, .orange, .yellow, .green, .cyan, .blue, .purple, .red],
            center: .center
        )
    }
    
    private var saveButtonGradient: LinearGradient {
        LinearGradient(
            colors: [.blue, .purple],
            startPoint: .leading,
            endPoint: .trailing
        )
    }
    
    @ViewBuilder
    private var recordingButtons: some View {
        HStack(spacing: 16) {
            if isRecording {
                stopRecordingButton
            } else if hasFinishedRecording {
                saveRecordingButton
            }
        }
    }
    
    private var stopRecordingButton: some View {
        Button(role: .destructive) {
            finishRecording(earlyStop: true)
        } label: {
            Label("提前结束", systemImage: "stop.circle.fill")
                .font(.system(.headline, design: .rounded))
                .padding(.horizontal, 18).padding(.vertical, 10)
                .background(.ultraThinMaterial)
                .cornerRadius(12)
        }
    }
    
    private var saveRecordingButton: some View {
        Button {
            showNoteSheet = true
        } label: {
            Label("保存记录", systemImage: "square.and.arrow.down.fill")
                .font(.system(.headline, design: .rounded))
                .padding(.horizontal, 18).padding(.vertical, 10)
                .background(saveButtonGradient)
                .cornerRadius(12)
        }
    }
    
    private var mainContent: some View {
        ZStack {
            backgroundGradient
            scenarioListScrollView
        }
    }
    
    private var scenarioListScrollView: some View {
        ScrollView {
            VStack(alignment: .leading, spacing: 20) {
                header
                scenarioGroups
            }
            .padding(20)
        }
    }
    
    private var scenarioGroups: some View {
        ForEach(Scenario.groupedByCategory(), id: \.category) { group in
            VStack(alignment: .leading, spacing: 12) {
                categoryHeader(category: group.category)
                scenarioGrid(scenarios: group.scenarios)
            }
        }
    }
    
    private func categoryHeader(category: ScenarioCategory) -> some View {
        HStack(spacing: 8) {
            Image(systemName: categoryIcon(for: category))
                .font(.system(size: 16, weight: .semibold))
                .foregroundColor(.white.opacity(0.9))
            Text(category.rawValue)
                .font(.system(.subheadline, design: .rounded).weight(.bold))
                .foregroundColor(.white.opacity(0.9))
        }
        .padding(.horizontal, 4)
    }
    
    private func scenarioGrid(scenarios: [Scenario]) -> some View {
        LazyVGrid(columns: columns, spacing: 12) {
            ForEach(scenarios) { scenario in
                ScenarioCard(scenario: scenario)
                    .onTapGesture {
                        print("🟧 [ScenarioList] 点击卡片 -> \(scenario.title) | 分类: \(scenario.category.rawValue)")
                        if scenario.category == .freeRecording {
                            // 直接进入自由记录页面
                            print("🟦 [ScenarioList] 打开自由记录页面")
                            // 清理所有可能遮挡的状态
                            selectedScenario = nil
                            activeScenario = nil
                            showCountdown = false
                            countdownValue = 3
                            timer?.invalidate(); timer = nil
                            if isRecording { sensor.stop() }
                            isRecording = false
                            hasFinishedRecording = false
                            showNoteSheet = false
                            uploadError = nil
                            uploadSuccess = false
                            // 打开自由记录
                            showFreeRecording = true
                        } else {
                            // 其它场景弹出确认并倒计时
                            pendingDuration = scenario.defaultDurationSec
                            selectedScenario = scenario
                        }
                    }
            }
        }
    }
    
    var body: some View {
        NavigationStack {
            mainContent
            .navigationTitle("采集场景")
            .navigationBarTitleDisplayMode(.inline)
            .sheet(item: $selectedScenario, content: confirmSheet)
            .overlay(countdownOverlay)
            .fullScreenCover(
                isPresented: Binding(
                    get: { isRecording || hasFinishedRecording },
                    set: { _ in }
                )
            ) {
                RecordingFullScreenView(
                    sensor: sensor,
                    isRecording: $isRecording,
                    hasFinishedRecording: $hasFinishedRecording,
                    recordingProgress: $recordingProgress,
                    recordingStartDate: $recordingStartDate,
                    recordingTotalSec: $recordingTotalSec,
            .sheet(isPresented: $showNoteSheet, content: noteSheet)
            .overlay(uploadingOverlay)
            .alert("上传失败", isPresented: .constant(uploadError != nil), actions: uploadFailureActions, message: uploadFailureMessage)
            .alert("上传成功", isPresented: $uploadSuccess, actions: uploadSuccessActions, message: uploadSuccessMessage)
            .alert("需要连接 AirPods", isPresented: $showAirPodsAlert, actions: airPodsAlertActions, message: airPodsAlertMessage)
            .fullScreenCover(isPresented: $showFreeRecording, content: freeRecordingCover)
            .onChange(of: showFreeRecording) { newValue in
                print("🟦 [ScenarioList] showFreeRecording -> \(newValue)")
            }
        }
        .preferredColorScheme(.dark)
        .onAppear { print("🟪 [ScenarioList] 页面出现") }
    }
    
    // MARK: - Sheet and Alert Helpers
    
    private func confirmSheet(scenario: Scenario) -> some View {
        Group {
            if scenario.category == .freeRecording {
                // 拦截自由记录：不弹确认框，改为打开全屏页面
                Color.clear
                    .onAppear {
                        print("🟩 [ScenarioList] 拦截自由记录，打开 FreeRecording 全屏页")
                        selectedScenario = nil
                        showFreeRecording = true
                    }
            } else {
                ScenarioConfirmSheet(
                    scenario: scenario,
                    duration: $pendingDuration,
                    onCancel: { selectedScenario = nil },
                    onConfirm: { startCountdown(for: scenario, seconds: pendingDuration) }
                )
                .presentationDetents([.height(360), .medium])
                .presentationCornerRadius(20)
            }
        }
    }
    
    private func noteSheet() -> some View {
        NoteInputSheet(noteText: $noteText) { note in
            if var session = lastSession {
                session.note = note
                sessions.append(session)
            }
            showNoteSheet = false
            hasFinishedRecording = false
            Task {
                await uploadDataToServer(note: note)
            }
            noteText = ""
        }
        .presentationDetents([.height(300), .medium])
        .presentationCornerRadius(20)
    }
    
    @ViewBuilder
    private var uploadingOverlay: some View {
        if isUploading {
            UploadingOverlay()
        }
    }
    
    private func uploadFailureActions() -> some View {
        Button("确定") {
            uploadError = nil
            lastSession = nil
            activeScenario = nil
        }
    }
    
    private func uploadFailureMessage() -> some View {
        Text(uploadError ?? "")
    }
    
    private func uploadSuccessActions() -> some View {
        Button("确定") {
            uploadSuccess = false
            lastSession = nil
            activeScenario = nil
            showNoteSheet = false
            hasFinishedRecording = false
        }
    }
    
    private func uploadSuccessMessage() -> some View {
        Text("数据已成功保存到服务器")
    }
    
    private func airPodsAlertActions() -> some View {
        Button("确定", role: .cancel) { }
    }
    
    private func airPodsAlertMessage() -> some View {
        Text("请连接支持的 AirPods（AirPods 3代、AirPods Pro 或 AirPods Max）并佩戴后再开始记录。\n\n确保已在设置中授权运动与健身权限。")
    }
    
    private func freeRecordingCover() -> some View {
        NavigationStack {
            FreeRecordingView()
                .environmentObject(sensor)
                .onAppear { print("🟩 [ScenarioList] FreeRecordingView 已呈现 (fullScreenCover)") }
        }
    }
    
    private var header: some View {
        VStack(alignment: .leading, spacing: 6) {
            HStack(spacing: 10) {
                Image(systemName: "record.circle.fill")
                    .foregroundStyle(.red, .white)
                    .font(.system(size: 22))
                Text("选择一个场景开始采集")
                    .font(.system(.title3, design: .rounded).weight(.semibold))
                
                Spacer()
            }
            Text("将以 50Hz 采集 AirPods 传感器数据（原始加速度计/陀螺仪与姿态补偿后的线性加速度），结束后自动导出 CSV。")
                .font(.footnote)
                .foregroundColor(.white.opacity(0.7))
        }
    }
    
    // MARK: - Countdown
    private var countdownOverlay: some View {
        Group {
            if showCountdown {
                ZStack {
                    Color.black.opacity(0.6).ignoresSafeArea()
                    VStack(spacing: 20) {
                        Text("准备开始")
                            .font(.system(.title2, design: .rounded).weight(.medium))
                            .foregroundColor(.white.opacity(0.9))
                        Text("\(countdownValue)")
                            .font(.system(size: 80, weight: .heavy, design: .rounded))
                            .foregroundStyle(LinearGradient(colors: [.blue, .cyan], startPoint: .topLeading, endPoint: .bottomTrailing))
                            .shadow(color: .blue.opacity(0.5), radius: 10, x: 0, y: 4)
                    }
                }
                .transition(.opacity)
            }
        }
        .animation(.easeInOut, value: showCountdown)
    }
    
    // Recording full screen moved to a dedicated child view below to avoid scope capture issues
    
    private var timeRemainingString: String {
        guard let start = recordingStartDate else { return "--:--" }
        let elapsed = Date().timeIntervalSince(start)
        let remaining = max(0, recordingTotalSec - elapsed)
        let m = Int(remaining) / 60
        let s = Int(remaining) % 60
        return String(format: "%02d:%02d", m, s)
    }
    
    // MARK: - Flow
    private func startCountdown(for scenario: Scenario, seconds: Double) {
        // 自由记录不走倒计时，直接进入
        if scenario.category == .freeRecording {
            print("🟩 [ScenarioList] 自由记录 startCountdown 拦截 -> 打开 FreeRecording")
            selectedScenario = nil
            showFreeRecording = true
            return
        }
        selectedScenario = nil
        activeScenario = scenario
        countdownValue = 3
        showCountdown = true
        
        Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { t in
            countdownValue -= 1
            if countdownValue <= 0 {
                t.invalidate()
                showCountdown = false
                beginRecording(scenario: scenario, seconds: seconds)
            }
        }
    }
    
    private func beginRecording(scenario: Scenario, seconds: Double) {
        // 自由记录不在此处开始，直接打开 FreeRecording 页面
        if scenario.category == .freeRecording {
            print("🟩 [ScenarioList] 自由记录 beginRecording 拦截 -> 打开 FreeRecording")
            selectedScenario = nil
            showFreeRecording = true
            return
        }
        activeScenario = scenario
        recordingTotalSec = seconds
        recordingStartDate = Date()
        recordingProgress = 0
        isRecording = true
        
        // 开始 50Hz 采集
        sensor.start(rateHz: 50)
        
        timer?.invalidate()
        timer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true) { t in
            guard let start = recordingStartDate else { return }
            let elapsed = Date().timeIntervalSince(start)
            recordingProgress = min(1.0, elapsed / recordingTotalSec)
            if elapsed >= recordingTotalSec {
                t.invalidate()
                finishRecording(earlyStop: false, scenario: scenario, actualDuration: elapsed)
            }
        }
    }
    
    private func finishRecording(earlyStop: Bool, scenario: Scenario? = nil, actualDuration: Double? = nil) {
        timer?.invalidate(); timer = nil
        sensor.stop()
        isRecording = false
        hasFinishedRecording = true  // 标记已完成记录
        
        // 生成会话（不在此处弹备注，由保存按钮触发）
        let usedScenario = scenario ?? activeScenario ?? selectedScenario
        if let scenario = usedScenario, let start = recordingStartDate {
            let end = Date()
            let duration = actualDuration ?? end.timeIntervalSince(start)
            let session = Session(scenario: scenario, startDate: start, endDate: end, durationSec: duration, note: nil)
            lastSession = session
            print("🧾 [ScenarioList] 记录完成，等待用户点击保存以填写备注")
        } else {
            // 若缺少上下文，也给出一个兜底的会话
            let scen = activeScenario ?? selectedScenario ?? Scenario.all.first!
            let now = Date()
            let session = Session(scenario: scen, startDate: now.addingTimeInterval(-1), endDate: now, durationSec: 1, note: nil)
            lastSession = session
            activeScenario = nil
        }
    }
    
    // MARK: - Upload to Server
    private func uploadDataToServer(note: String) async {
        guard let session = lastSession, let scenario = activeScenario else {
            await MainActor.run {
                uploadError = "缺少会话信息"
            }
            return
        }
        
        await MainActor.run {
            isUploading = true
        }
        
        do {
            // 1. 导出 CSV 文件
            let rawURL = try sensor.exportCSV(userName: userName, note: note)
            
            // 2. 生成 OSS 对象键（文件路径）- URL 编码用户名
            let timestamp = Int(Date().timeIntervalSince1970)
            let encodedUserName = userName.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? userName
            let rawObjectKey = "chew_data/\(encodedUserName)/\(timestamp)_raw.csv"
            
            // 3. 上传到阿里云 OSS
            let rawOSSUrl = try await OSSUploadService.shared.uploadFile(fileURL: rawURL, objectKey: rawObjectKey)
            
            // 4. 调用后端接口保存数据
            try await ChewDataService.shared.saveChewData(
                scenario: scenario.title,
                note: note.isEmpty ? "未备注" : note,
                userName: userName,
                duration: session.durationSec,
                rawCsvUrl: rawOSSUrl
            )
            
            // 5. 成功
            await MainActor.run {
                isUploading = false
                uploadSuccess = true
            }
            
        } catch {
            await MainActor.run {
                isUploading = false
                uploadError = error.localizedDescription
            }
        }
    }
    
    // MARK: - Helper
    private func categoryIcon(for category: ScenarioCategory) -> String {
        switch category {
        case .freeRecording:
            return "record.circle.fill"
        case .sittingChewing:
            return "person.crop.circle.fill"
        case .sittingNonChewing:
            return "person.fill"
        case .walkingOnly:
            return "figure.walk.circle.fill"
        case .walkingChewing:
            return "figure.walk"
        case .walkingNonChewing:
            return "figure.walk.motion"
        }
    }
}

// MARK: - Uploading Overlay
private struct UploadingOverlay: View {
    var body: some View {
        ZStack {
            Color.black.opacity(0.5).ignoresSafeArea()
            VStack(spacing: 20) {
                ProgressView()
                    .scaleEffect(1.5)
                    .tint(.white)
                Text("正在上传数据...")
                    .font(.system(.body, design: .rounded).weight(.medium))
                    .foregroundColor(.white)
            }
            .padding(40)
            .background(.ultraThinMaterial, in: RoundedRectangle(cornerRadius: 20))
        }
    }
}

// MARK: - Components
private struct ScenarioCard: View {
    let scenario: Scenario
    
    var body: some View {
        ZStack {
            // 背景渐变
            LinearGradient(colors: scenario.gradient, startPoint: .topLeading, endPoint: .bottomTrailing)
            
            // 装饰性背景图标
            GeometryReader { geometry in
                Image(systemName: scenario.icon)
                    .font(.system(size: 80, weight: .thin))
                    .foregroundColor(.white.opacity(0.08))
                    .frame(width: geometry.size.width, height: geometry.size.height)
                    .position(x: geometry.size.width * 0.75, y: geometry.size.height * 0.6)
            }
            
            // 内容层
            VStack(alignment: .leading, spacing: 0) {
                // 标题和图标
                HStack(spacing: 10) {
                    Image(systemName: scenario.icon)
                        .font(.system(size: 24, weight: .semibold))
                        .foregroundColor(.white)
                    
                    VStack(alignment: .leading, spacing: 2) {
                        Text(scenario.title)
                            .font(.system(.body, design: .rounded).weight(.bold))
                            .foregroundColor(.white)
                            .lineLimit(1)
                            .minimumScaleFactor(0.8)
                        
                        Text(scenario.subtitle)
                            .font(.system(.caption2, design: .rounded))
                            .foregroundColor(.white.opacity(0.85))
                            .lineLimit(1)
                    }
                }
                
                Spacer()
                
                Spacer().frame(height: 8)
                
                // 底部：时长信息
                HStack(spacing: 4) {
                    Image(systemName: "clock.fill")
                        .font(.system(size: 10, weight: .semibold))
                        .foregroundColor(.white.opacity(0.9))
                    Text(durationLabel)
                        .font(.system(.caption2, design: .rounded).weight(.medium))
                        .foregroundColor(.white.opacity(0.9))
                }
                .padding(.horizontal, 8)
                .padding(.vertical, 4)
                .background(.white.opacity(0.2))
                .cornerRadius(8)
            }
            .padding(14)
        }
        .frame(height: 140)
        .clipShape(RoundedRectangle(cornerRadius: 20, style: .continuous))
        .overlay(
            RoundedRectangle(cornerRadius: 20, style: .continuous)
                .strokeBorder(
                    LinearGradient(
                        colors: [.white.opacity(0.3), .white.opacity(0.1)],
                        startPoint: .topLeading,
                        endPoint: .bottomTrailing
                    ),
                    lineWidth: 1.5
                )
        )
        .shadow(color: scenario.gradient.last?.opacity(0.4) ?? .black.opacity(0.3), radius: 15, x: 0, y: 8)
        .contentShape(Rectangle())
    }
    
    private var durationLabel: String {
        // 自由记录显示"不限制"
        if scenario.category == .freeRecording {
            return "建议时长：不限制"
        }
        
        if scenario.hasRange {
            return "建议时长：\(format(min: scenario.minDurationSec, max: scenario.maxDurationSec))"
        } else {
            return "建议时长：\(format(seconds: scenario.minDurationSec))"
        }
    }
    
    private func format(min: Double, max: Double) -> String {
        let a = format(seconds: min)
        let b = format(seconds: max)
        return "\(a) – \(b)"
    }
    private func format(seconds: Double) -> String {
        if seconds >= 60 {
            return String(format: "%.0f 分钟", seconds/60)
        } else {
            return String(format: "%.0f 秒", seconds)
        }
    }
}

private struct ScenarioConfirmSheet: View {
    let scenario: Scenario
    @Binding var duration: Double
    var onCancel: () -> Void
    var onConfirm: () -> Void
    
    var body: some View {
        VStack(spacing: 16) {
            Capsule().fill(.secondary.opacity(0.4)).frame(width: 40, height: 5).padding(.top, 8)
            HStack(spacing: 12) {
                Image(systemName: scenario.icon)
                    .font(.system(size: 22, weight: .semibold))
                    .foregroundStyle(LinearGradient(colors: scenario.gradient, startPoint: .topLeading, endPoint: .bottomTrailing))
                VStack(alignment: .leading) {
                    Text(scenario.title).font(.headline)
                    Text(scenario.subtitle).font(.subheadline).foregroundColor(.secondary)
                }
                Spacer()
            }
            
            VStack(alignment: .leading, spacing: 8) {
                Text("请根据提示准备：")
                    .font(.subheadline).fontWeight(.semibold)
                Text("• 请确保 AirPods 已连接并佩戴\n• 按提示开始后将倒计时 3,2,1\n• 期间尽量保持符合该场景的动作")
                    .font(.footnote)
                    .foregroundColor(.secondary)
            }
            .frame(maxWidth: .infinity, alignment: .leading)
            .padding()
            .background(.ultraThinMaterial, in: RoundedRectangle(cornerRadius: 16))
            
            if scenario.hasRange {
                VStack(alignment: .leading) {
                    HStack {
                        Text("选择时长")
                        Spacer()
                        Text(durationString)
                            .foregroundColor(.secondary)
                    }
                    Slider(value: $duration, in: scenario.minDurationSec...scenario.maxDurationSec, step: 10)
                }
            } else {
                HStack {
                    Text("时长")
                    Spacer()
                    Text(durationString)
                        .foregroundColor(.secondary)
                }
                .onAppear { duration = scenario.minDurationSec }
            }
            
            HStack(spacing: 12) {
                Button("取消", role: .cancel) { onCancel() }
                    .buttonStyle(.bordered)
                Button {
                    onConfirm()
                } label: {
                    Label("开始", systemImage: "play.fill")
                }
                .buttonStyle(.borderedProminent)
            }
            .padding(.top, 4)
            
            Spacer(minLength: 0)
        }
        .padding(20)
    }
    
    private var durationString: String {
        if duration >= 60 { return String(format: "%.0f 分钟", duration/60) }
        return String(format: "%.0f 秒", duration)
    }
}

private struct NoteInputSheet: View {
    @Binding var noteText: String
    var onSave: (String) -> Void
    @Environment(\.dismiss) private var dismiss
    
    var body: some View {
        VStack(spacing: 20) {
            // 顶部拖动条
            Capsule()
                .fill(Color.white.opacity(0.3))
                .frame(width: 40, height: 5)
                .padding(.top, 12)
            
            // 标题
            VStack(spacing: 8) {
                Image(systemName: "note.text")
                    .font(.system(size: 40, weight: .semibold))
                    .foregroundStyle(
                        LinearGradient(
                            colors: [.blue, .purple],
                            startPoint: .topLeading,
                            endPoint: .bottomTrailing
                        )
                    )
                
                Text("记录备注")
                    .font(.system(.title3, design: .rounded).weight(.bold))
                    .foregroundColor(.white)
                
                Text("请输入吃的东西（必填）")
                    .font(.system(.footnote, design: .rounded))
                    .foregroundColor(.white.opacity(0.7))
            }
            
            // 输入框
            TextField("如：花生/苹果/没咀嚼", text: $noteText)
                .textFieldStyle(.roundedBorder)
                .padding(.horizontal, 4)
            
            // 错误提示
            if noteText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
                HStack(spacing: 6) {
                    Image(systemName: "exclamationmark.circle.fill")
                        .foregroundColor(.orange)
                    Text("必须填写吃的东西才能保存")
                        .font(.system(.caption, design: .rounded))
                        .foregroundColor(.orange)
                }
            }
            
            // 按钮
            HStack(spacing: 12) {
                Button("取消") {
                    dismiss()
                }
                .buttonStyle(.bordered)
                .tint(.white)
                
                Button("保存") {
                    onSave(noteText)
                }
                .buttonStyle(.borderedProminent)
                .tint(LinearGradient(
                    colors: [.blue, .purple],
                    startPoint: .leading,
                    endPoint: .trailing
                ))
                .disabled(noteText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
            }
            .padding(.top, 8)
        }
        .padding(24)
        .frame(maxWidth: .infinity)
        .background(
            LinearGradient(
                colors: [
                    Color(red: 0.15, green: 0.15, blue: 0.2),
                    Color(red: 0.1, green: 0.1, blue: 0.15)
                ],
                startPoint: .topLeading,
                endPoint: .bottomTrailing
            )
        )
        .cornerRadius(24)
        .presentationDetents([.height(320)])
        .presentationDragIndicator(.hidden)
    }
}

// MARK: - Sensor Data Card
private struct SensorDataCard: View {
    let title: String
    let icon: String
    let color: Color
    let xValue: Double
    let yValue: Double
    let zValue: Double
    let unit: String
    
    var body: some View {
        VStack(spacing: 8) {
            HStack(spacing: 8) {
                Image(systemName: icon)
                    .font(.system(size: 16, weight: .semibold))
                    .foregroundColor(color)
                Text(title)
                    .font(.system(.subheadline, design: .rounded).weight(.semibold))
                    .foregroundColor(.white)
                Spacer()
            }
            
            HStack(spacing: 12) {
                SensorAxisView(axis: "X", value: xValue, unit: unit, color: .red)
                SensorAxisView(axis: "Y", value: yValue, unit: unit, color: .green)
                SensorAxisView(axis: "Z", value: zValue, unit: unit, color: .blue)
            }
        }
        .padding(12)
        .background(.white.opacity(0.1))
        .cornerRadius(12)
    }
}

private struct SensorAxisView: View {
    let axis: String
    let value: Double
    let unit: String
    let color: Color
    
    var body: some View {
        VStack(spacing: 4) {
            Text(axis)
                .font(.system(.caption2, design: .rounded).weight(.bold))
                .foregroundColor(color)
            Text(String(format: "%.3f", value))
                .font(.system(.caption, design: .monospaced).weight(.medium))
                .foregroundColor(.white)
            
            // 可视化指示器
            ZStack {
                RoundedRectangle(cornerRadius: 2)
                    .fill(.white.opacity(0.2))
                    .frame(width: 4, height: 40)
                
                VStack {
                    if value > 0 {
                        Spacer()
                    }
                    RoundedRectangle(cornerRadius: 2)
                        .fill(color)
                        .frame(width: 4, height: min(abs(value) * 20, 20))
                    if value < 0 {
                        Spacer()
                    }
                }
                .frame(height: 40)
            }
        }
        .frame(maxWidth: .infinity)
    }
}
